package com.aluka.nirvana.framework.security.handler;

import com.aluka.nirvana.framework.security.utils.ResponseUtils;
import com.google.common.base.Throwables;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义 Security 登陆失败处理类
 * @author gongli
 * @since 2019/4/10 13:40
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException{
        ResponseUtils.writeResponse(httpServletResponse,
                HttpStatus.INTERNAL_SERVER_ERROR,
                e == null ? "用户名或密码错误!" : Throwables.getRootCause(e).getMessage());
    }
}
